var express = require('express');
var router = express.Router();
var axios = require('axios');
var crypto = require('crypto');
var mq = require('mysql-queries').init({
  host: 'localhost',
  port: 3306,
  user: 'root',
  password: 'root',
  database: 'realmd'
});

var {adminDao,
  logDao,
  playerDao,
  raidDao,
  save,
  getUserByReq
} = require('../data')

router.get('/', function(req, res, next) {
  res.status(404);
  res.end();
});


//角色列表
router.post('/list',function(req,res,next){
  var {
    name,
    classes,
    sort,
    order,
    pageNo=1,
    pageSize=10
  } = req.body,result = [];
  if(classes){
    classes = classes.split(',');
  }
  

  playerDao.search({name,classes,sort,order,pageNo,pageSize})
  .then(rst=>{
    res.json({
      status: 0,
      data: rst.data
    })
  },err=>{
    res.json({
      status: 3,
      msg: '未知错误'
    })
  })
});

router.post('/allNames',function(req,res,next){
  playerDao.allNames().then(rst=>{
    res.json({
      status: 0,
      data: rst.data
    })
  })
})

router.post('/allClasses', function (req, res, next) {
  playerDao.allClasses().then(rst => {
    res.json({
      status: 0,
      data: rst.data
    })
  })
})

router.post('/playerExists',function(req,res,next){
  let {name} = req.body
  playerDao.playerExists(name).then(rst=>{
    res.json({
      status: 0,
      data: rst.data
    })
  })
})

router.get('/itemDetail',function(req,res,next){
  let {itemId} = req.query;
  axios.get(`http://cn.60wdb.com/get/item/${itemId}`).then(rep=>{
    res.json({
      status:0,
      data:rep.data
    })
  }, err=>{
    console.log(err,'e')
    res.json({
      status: -1,
      msg: err
    })
  }).catch(err=>{
    console.log(err,'c')
    res.json({
      status: -2,
      msg: err
    })
  })
})

router.post('/regAcc', function (req, res, next) {
  let {
    username,
    password,
    email
  } = req.body
  username = username.toUpperCase();
  password = password.toUpperCase();
  email = email.toUpperCase();

  mq.query('select id from account where username=?', [username], function(err, rst) {
    if (err){
      res.json({
        status: -1,
        msg: '数据库连接失败'
      })
    } else if (rst.length > 0) {
        res.json({
          status: -1,
          msg: '该用户名已存在'
        })
    } else {
      // mq.query('select id from account where email=?', [email], function(err, rst) {
      //   if (err) {
      //     res.json({
      //       status: -1,
      //       msg: '数据库连接失败'
      //     })
      //   } else if (rst.length > 0 ) {
      //     res.json({
      //       status: -1,
      //       msg: '该邮箱已使用'
      //     })
      //   } else {
          password = crypto.createHash('sha1').update(username + ':' + password).digest('hex');
          mq.query('insert into account(username, sha_pass_hash, email) values(?, ?, ?)', [username, password, email], function (err) {
            if (err) {
              res.json({
                status: -1,
                msg: '数据库连接失败'
              })
            } else {
              res.json({
                status: 0,
                msg: ''
              })
            }
          })
      //   }
      // })
    }
  })
})

router.post('/gameAccountList', function(req, res, next) {
  let {pageNo, pageSize} = req.body
  pageNo = +pageNo;
  pageSize = +pageSize;
  mq.queries([
    'select count(*) as cnt from account',
    'select id,username,email,last_login from account limit ?,?'
  ],[[],[(pageNo - 1) * pageSize, pageSize]], function(err, rst){
    if (err){
      res.json({
        status: -1,
        msg: '数据库连接失败'
      })
    } else {
      const data = {
        total: rst[0][0].cnt,
        list: rst[1]
      }

      let ids = rst[1].map(o=>o.id);
      let sql = `select guid,account,name,race,class,gender,level,online from characters.characters where account in (${ids.map(o=>'?').join(',')})`;
      mq.query(sql,ids,function(err, rst){
        let user = getUserByReq(req)
        data.list.forEach(acc=>{
          acc.characters = rst.filter(o=>o.account == acc.id);
          if(!user || user.level < 3) {
            acc.email = (acc.email || '').replace(/(\w{2})\w+(\w)@(\w+)/, "$1*****$2@$3");
          }
        })

        res.json({
          status: 0,
          data
        })
      });
    }
  })
})

module.exports = router;